<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content>
    <meta name="keyword" content>
    <link rel="shortcut icon" href="/img/ironman-draw.png">
    <!-- Place this tag in your head or just before your close body tag. -->
    <script async defer src="https://buttons.github.io/buttons.js"></script>
    <title>
        
          Quartz.NET实现作业调度 - xyzko1 | 博客
        
    </title>

    <link rel="canonical" href="https://xyzko1.github.io/2019/06/23/Quartz.NET实现作业调度/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS --> 
    <link rel="stylesheet" href="/css/beantech.min.css">
    
    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/css/highlight.css">

    <link rel="stylesheet" href="/css/widget.css">

    <link rel="stylesheet" href="/css/rocket.css">

    <link rel="stylesheet" href="/css/signature.css">

    <link rel="stylesheet" href="/css/toc.css">

    <!-- Custom Fonts -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">


    <!-- Hux Delete, sad but pending in China
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/
    css'>
    -->


    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- ga & ba script hoook -->
    <script></script>
</head>


<!-- hack iOS CSS :active style -->
<body ontouchstart="">
	<!-- Modified by Yu-Hsuan Yen -->
<!-- Post Header -->
<style type="text/css">
    header.intro-header{
        
            background-image: url('Demo.png')
            /*post*/
        
    }
    
    #signature{
        background-image: url('/img/signature/BeanTechSign-white.png');
    }
    
</style>

<header class="intro-header" >
    <!-- Signature -->
    <div id="signature">
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                
                    <div class="post-heading">
                        <div class="tags">
                            
                              <a class="tag" href="/tags/#Hexo" title="Hexo">Hexo</a>
                            
                              <a class="tag" href="/tags/#Blog" title="Blog">Blog</a>
                            
                        </div>
                        <h1>Quartz.NET实现作业调度</h1>
                        <h2 class="subheading"></h2>
                        <span class="meta">
                            Posted by xyzko1 on
                            2019-06-23
                        </span>
                    </div>
                


                </div>
            </div>
        </div>
    </div>
</header>

	
    <!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">xyz的博客</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/">Home</a>
                    </li>

                    

                        
                    

                        
                        <li>
                            <a href="/about/">About</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/tags/">Tags</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/archive/">Archives</a>
                        </li>
                        
                    
                    
                </ul>
            </div>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>


    <!-- Main Content -->
    <!-- Modify by Yu-Hsuan Yen -->

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

            <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

                <blockquote>
<p>created by <a href="https://github.com/xyzko1/xyzko1.github.io" target="_blank" rel="noopener">xyzko1</a><br>
2019年06月23日 19:00:00</p>
</blockquote>
<h1><span id="quartznet介绍">Quartz.NET介绍</span></h1>
<hr>
<p>Quartz.NET是一个强大、开源、轻量的作业调度框架，是 OpenSymphony 的 Quartz API 的.NET移植，用C#改写，可用于winform和asp.net应用中。它灵活而不复杂。你能够用它来为执行一个作业而创建简单的或复杂的作业调度。它有很多特征，如：数据库支持，集群，插件，支持cron-like表达式等等。<br>
通俗说它的功能是：比如说我想每天晚上2点让程序或网站执行某些代码，或者每隔5秒种我想查看是否有新的任务要处理等。<br>
官网：<a href="http://www.quartz-scheduler.net/" target="_blank" rel="noopener">http://www.quartz-scheduler.net/</a><br>
源码：<a href="https://github.com/quartznet/quartznet" target="_blank" rel="noopener">https://github.com/quartznet/quartznet</a><br>
示例：<a href="http://www.quartz-scheduler.net/documentation/quartz-2.x/quick-start.html" target="_blank" rel="noopener">http://www.quartz-scheduler.net/documentation/quartz-2.x/quick-start.html</a><br>
其实Quartz是一个完全由java编写的开源作业调度框架，Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目，它可以与J2EE与J2SE应用程序相结合也可以单独使用。Quartz可以用来创建简单或为运行十个，百个，甚至是好几万个Jobs这样复杂的程序。而Quartz.Net与NPOI一样是一个DoNet平台下的对应版本。如果您使用Java直接访问这里就好了http://www.quartz-scheduler.org/</p>
<h1><span id="依赖框架">依赖框架</span></h1>
<hr>
<p>引入框架的方法非常简单你可以直接用nuget管理包也可以在项目中添加引用：</p>
<h2><span id="创建一个项目">创建一个项目</span></h2>
<p>创建一个新项目，<a href="http://xn--ASP-vs9dj4u7u4a.NET" target="_blank" rel="noopener">可以是ASP.NET</a> MVC,WebForms,Winforms等多种.Net项目，这里使用的是VS2013，创建了一个MVC项目：<br>
<img src="1.png" alt="avatar"></p>
<h2><span id="安装nuget">安装Nuget</span></h2>
<p>新版本的Visual Studio默认情况是安装了Nuget的，如Visual Studio2015，但如果没有安装，打开VS菜单“工具”-&gt;&quot;扩展与更新&quot;<br>
<img src="2.png" alt="avatar"><br>
在扩展与更新中搜索“nuget”，可以新安装或卸载后升级：<br>
<img src="3.png" alt="avatar"></p>
<h2><span id="修改nuget镜像">修改Nuget镜像</span></h2>
<p>为解决国内访问NuGet服务器速度不稳定的问题建议你最好选择一些镜像服务器，这样可以加速下载。<br>
在Visual Studio中的添加方法是：打开“工具”-&gt;“选项”菜单<br>
<img src="4.png" alt="avatar"><br>
在左侧菜单中找到“NuGet包管理器”<br>
<img src="5.png" alt="avatar"><br>
点击右上角的加号，添加两个镜像，这些地址可以上网搜索，我使用的是如下两个：<br>
<a href="https://nuget.cnblogs.com/v3/index.json" target="_blank" rel="noopener">https://nuget.cnblogs.com/v3/index.json</a><br>
<a href="http://api.nuget.org/v3/index.json" target="_blank" rel="noopener">http://api.nuget.org/v3/index.json</a><br>
设置一下顺序就OK了。</p>
<h2><span id="使用nuget安装quartznet"></span></h2>
<p>点击“工具”-&gt;“NuGet包管理器”-&gt;“程序包管理器控制台”<br>
<img src="6.png" alt="avatar"><br>
输入安装包的命令：<br>
Install-Package Quartz<br>
安装结果如下：<br>
<img src="7.png" alt="avatar"><br>
此时包管理器中就下载了需要的程序集与相关文件，程序中也添加了引用。<br>
<img src="8.png" alt="avatar"></p>
<h2><span id="手动引用">手动引用</span></h2>
<p>当然如果您不愿意使用nuget也可以下载到Quartz后直接引用，可以在本文尾部下载到框架。<br>
<img src="9.png" alt="avatar"><br>
框架下载地址：链接: <a href="https://pan.baidu.com/s/1slDM5JJ" target="_blank" rel="noopener">https://pan.baidu.com/s/1slDM5JJ</a> 密码: 9x5m</p>
<h1><span id="应用框架">应用框架</span></h1>
<hr>
<p>假定我现在想当前的MVC应用每隔5秒钟向C:\Quartz.txt文件中记录当前时间。<br>
因为这是一个Web应用，我想网站一启动时就开始该项工作，这里我们需要打开Global.asax，将代码写在Application_Start方法中</p>
<h2><span id="定义要执行的任务">定义要执行的任务</span></h2>
<p>定义一个类，实现Quartz.IJob接口，实现方法Execute，TimeJob.cs文件的代码如下：</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> Quartz;</span><br><span class="line"><span class="keyword">using</span> System;</span><br><span class="line"><span class="keyword">using</span> System.Collections.Generic;</span><br><span class="line"><span class="keyword">using</span> System.Linq;</span><br><span class="line"><span class="keyword">using</span> System.Web;</span><br><span class="line"></span><br><span class="line"><span class="keyword">namespace</span> MvcApplication1</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TimeJob</span> :</span> IJob</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Execute</span><span class="params">(IJobExecutionContext context)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            <span class="comment">//向c:\Quartz.txt写入当前时间并换行</span></span><br><span class="line">            System.IO.<span class="built_in">File</span>.AppendAllText(@<span class="string">"c:\Quartz.txt"</span>, DateTime.Now+Environment.NewLine);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2><span id="创建一个调度器">创建一个调度器</span></h2>
<p>调度器负责管理与控制任务的执行，在Global.asax文件的Application_Start方法中添加如下代码：</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//调度器</span></span><br><span class="line">         IScheduler scheduler;</span><br><span class="line">         <span class="comment">//调度器工厂</span></span><br><span class="line">         ISchedulerFactory <span class="keyword">factory</span>;</span><br><span class="line"></span><br><span class="line">         <span class="comment">//创建一个调度器</span></span><br><span class="line">         <span class="keyword">factory</span> = <span class="keyword">new</span> StdSchedulerFactory();</span><br><span class="line">         scheduler = <span class="keyword">factory</span>.GetScheduler();</span><br><span class="line">         scheduler.Start();</span><br></pre></td></tr></table></figure>
<h2><span id="创建一个任务对象">创建一个任务对象</span></h2>
<p>这个任务对象就是我们将要执行的工作，job1是名称，group1是组名。</p>
<figure class="highlight cos"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//2、创建一个任务</span></span><br><span class="line">          IJobDetail <span class="keyword">job</span> = JobBuilder.Create&lt;TimeJob&gt;().WithIdentity(<span class="string">"job1"</span>, <span class="string">"group1"</span>).Build()<span class="comment">;</span></span><br></pre></td></tr></table></figure>
<h2><span id="创建一个触发器">创建一个触发器</span></h2>
<p>触发器定义了什么时间任务开始或每隔多久执行一次。</p>
<figure class="highlight protobuf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//3、创建一个触发器</span></span><br><span class="line">         <span class="comment">//DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);</span></span><br><span class="line">         ITrigger trigger = TriggerBuilder.Create()</span><br><span class="line">             .WithIdentity(<span class="string">"trigger1"</span>, <span class="string">"group1"</span>)</span><br><span class="line">             .WithCronSchedule(<span class="string">"0/5 * * * * ?"</span>)     <span class="comment">//5秒执行一次</span></span><br><span class="line">             <span class="comment">//.StartAt(runTime)</span></span><br><span class="line">             .Build();</span><br></pre></td></tr></table></figure>
<h2><span id="将任务与触发器添加到调度器中并执行">将任务与触发器添加到调度器中并执行</span></h2>
<p>触发器定义了什么时间任务开始或每隔多久执行一次。</p>
<figure class="highlight gcode"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//4、将任务与触发器添加到调度器中</span></span><br><span class="line">       scheduler.ScheduleJob<span class="comment">(job, trigger)</span>;</span><br><span class="line">       <span class="comment">//5、开始执行</span></span><br><span class="line">       scheduler.Start<span class="comment">()</span></span><br></pre></td></tr></table></figure>
<h2><span id="应用关闭时结束任务">应用关闭时结束任务</span></h2>
<p>当网站关闭时结束正在执行的工作，在Global.asax中的Application_End方法中添加如下代码：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">Application_End</span>(<span class="params"><span class="keyword">object</span> sender, EventArgs e</span>)</span></span><br><span class="line"><span class="function"></span>  &#123;</span><br><span class="line">      <span class="comment">//   在应用程序关闭时运行的代码</span></span><br><span class="line">      <span class="keyword">if</span> (scheduler != <span class="literal">null</span>)</span><br><span class="line">      &#123;</span><br><span class="line">          scheduler.Shutdown(<span class="literal">true</span>);</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p>shutdown方法中的参数true的意思为：是否等待任务的完成再结束。</p>
<h2><span id="运行结果">运行结果</span></h2>
<p><img src="10.png" alt="avatar"></p>
<h2><span id="globalasax中的完整代码">Global.asax中的完整代码</span></h2>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line">     <span class="keyword">using</span> Quartz;</span><br><span class="line"><span class="keyword">using</span> Quartz.Impl;</span><br><span class="line"><span class="keyword">using</span> System;</span><br><span class="line"><span class="keyword">using</span> System.Collections.Generic;</span><br><span class="line"><span class="keyword">using</span> System.Linq;</span><br><span class="line"><span class="keyword">using</span> System.Web;</span><br><span class="line"><span class="keyword">using</span> System.Web.Http;</span><br><span class="line"><span class="keyword">using</span> System.Web.Mvc;</span><br><span class="line"><span class="keyword">using</span> System.Web.Optimization;</span><br><span class="line"><span class="keyword">using</span> System.Web.Routing;</span><br><span class="line"></span><br><span class="line"><span class="keyword">namespace</span> MvcApplication1</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MvcApplication</span> :</span> System.Web.HttpApplication</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">//调度器</span></span><br><span class="line">        IScheduler scheduler;</span><br><span class="line">        <span class="comment">//调度器工厂</span></span><br><span class="line">        ISchedulerFactory factory;</span><br><span class="line">        <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">Application_Start</span><span class="params">()</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            AreaRegistration.RegisterAllAreas();</span><br><span class="line"></span><br><span class="line">            WebApiConfig.Register(GlobalConfiguration.Configuration);</span><br><span class="line">            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);</span><br><span class="line">            RouteConfig.RegisterRoutes(RouteTable.Routes);</span><br><span class="line">            BundleConfig.RegisterBundles(BundleTable.Bundles);</span><br><span class="line">            AuthConfig.RegisterAuth();</span><br><span class="line"></span><br><span class="line">            <span class="comment">//1、创建一个调度器</span></span><br><span class="line">            factory = <span class="keyword">new</span> StdSchedulerFactory();</span><br><span class="line">            scheduler = factory.GetScheduler();</span><br><span class="line">            scheduler.Start();</span><br><span class="line"></span><br><span class="line">            <span class="comment">//2、创建一个任务</span></span><br><span class="line">            IJobDetail job = JobBuilder.Create&lt;TimeJob&gt;().WithIdentity(<span class="string">"job1"</span>, <span class="string">"group1"</span>).Build();</span><br><span class="line"></span><br><span class="line">            <span class="comment">//3、创建一个触发器</span></span><br><span class="line">            <span class="comment">//DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);</span></span><br><span class="line">            ITrigger trigger = TriggerBuilder.Create()</span><br><span class="line">                .WithIdentity(<span class="string">"trigger1"</span>, <span class="string">"group1"</span>)</span><br><span class="line">                .WithCronSchedule(<span class="string">"0/5 * * * * ?"</span>)     <span class="comment">//5秒执行一次</span></span><br><span class="line">                <span class="comment">//.StartAt(runTime)</span></span><br><span class="line">                .Build();</span><br><span class="line"></span><br><span class="line">            <span class="comment">//4、将任务与触发器添加到调度器中</span></span><br><span class="line">            scheduler.ScheduleJob(job, trigger);</span><br><span class="line">            <span class="comment">//5、开始执行</span></span><br><span class="line">            scheduler.Start();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">Application_End</span><span class="params">(object sender, EventArgs e)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            <span class="comment">//   在应用程序关闭时运行的代码</span></span><br><span class="line">            <span class="keyword">if</span> (scheduler != null)</span><br><span class="line">            &#123;</span><br><span class="line">                scheduler.Shutdown(<span class="literal">true</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1><span id="框架说明">框架说明</span></h1>
<hr>
<p>看官方的示例、源码或帮助文档可以了解更多的使用方法，官方帮助的地址是：<a href="https://www.quartz-scheduler.net/documentation/index.html" target="_blank" rel="noopener">https://www.quartz-scheduler.net/documentation/index.html</a></p>
<h2><span id="quartz的cron表达式">Quartz的cron表达式</span></h2>
<p>cron表达式就是用于设定时间的一个字符串，在前面的代码中我们就用到了，如下所示：</p>
<figure class="highlight protobuf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//3、创建一个触发器</span></span><br><span class="line"><span class="comment">//DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);</span></span><br><span class="line">ITrigger trigger = TriggerBuilder.Create()</span><br><span class="line">    .WithIdentity(<span class="string">"trigger1"</span>, <span class="string">"group1"</span>)</span><br><span class="line">    .WithCronSchedule(<span class="string">"0/5 * * * * ?"</span>)     <span class="comment">//5秒执行一次</span></span><br><span class="line">    <span class="comment">//.StartAt(runTime)</span></span><br><span class="line">    .Build();</span><br></pre></td></tr></table></figure>
<p>官方英文介绍：<a href="http://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/crontrigger.html" target="_blank" rel="noopener">http://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/crontrigger.html</a><br>
cron expressions 整体上还是非常容易理解的，只有一点需要注意：&quot;?&quot;号的用法，看下文可以知道“？”可以用在 day of month 和 day of week中，他主要是为了解决如下场景，如：每月的1号的每小时的31分钟，正确的表达式是：* 31 * 1 * ？，而不能是：* 31 * 1 * *，因为这样代表每周的任意一天。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">由7段构成：秒 分 时 日 月 星期 年（可选）</span><br><span class="line"></span><br><span class="line">&quot;-&quot; ：表示范围  MON-WED表示星期一到星期三</span><br><span class="line">&quot;,&quot; ：表示列举 MON,WEB表示星期一和星期三</span><br><span class="line">&quot;*&quot; ：表是“每”，每月，每天，每周，每年等</span><br><span class="line">&quot;/&quot; :表示增量：0/15（处于分钟段里面） 每15分钟，在0分以后开始，3/20 每20分钟，从3分钟以后开始</span><br><span class="line">&quot;?&quot; :只能出现在日，星期段里面，表示不指定具体的值</span><br><span class="line">&quot;L&quot; :只能出现在日，星期段里面，是Last的缩写，一个月的最后一天，一个星期的最后一天（星期六）</span><br><span class="line">&quot;W&quot; :表示工作日，距离给定值最近的工作日</span><br><span class="line">&quot;#&quot; :表示一个月的第几个星期几，例如：&quot;6#3&quot;表示每个月的第三个星期五（1=SUN...6=FRI,7=SAT）</span><br><span class="line"></span><br><span class="line">如果Minutes的数值是 &apos;0/15&apos; ，表示从0开始每15分钟执行</span><br><span class="line"></span><br><span class="line">如果Minutes的数值是 &apos;3/20&apos; ，表示从3开始每20分钟执行，也就是‘3/23/43’</span><br><span class="line">*/</span><br></pre></td></tr></table></figure>
<p>官方示例：</p>
<table>
<thead>
<tr>
<th>表达式</th>
<th>解释</th>
</tr>
</thead>
<tbody>
<tr>
<td>0 0 12 * * ?</td>
<td>每天中午12点触发</td>
</tr>
<tr>
<td>0 15 10 ? * *</td>
<td>每天上午10:15触发</td>
</tr>
<tr>
<td>0 15 10 * * ?</td>
<td>每天上午10:15触发</td>
</tr>
<tr>
<td>0 15 10 * * ? *</td>
<td>每天上午10:15触发</td>
</tr>
<tr>
<td>0 15 10 * * ? 2005 2005</td>
<td>年的每天上午10:15触发</td>
</tr>
<tr>
<td>0 * 14 * * ?</td>
<td>在每天下午2点到下午2:59期间的每1分钟触发</td>
</tr>
<tr>
<td>0 0/5 14 * * ?</td>
<td>在每天下午2点到下午2:55期间的每5分钟触发</td>
</tr>
<tr>
<td>0 0/5 14,18 * * ?</td>
<td>在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发</td>
</tr>
<tr>
<td>0 0-5 14 * * ?</td>
<td>在每天下午2点到下午2:05期间的每1分钟触发</td>
</tr>
<tr>
<td>0 10,44 14 ? 3 WED</td>
<td>每年三月的星期三的下午2:10和2:44触发</td>
</tr>
<tr>
<td>0 15 10 ? * MON-FRI</td>
<td>周一至周五的上午10:15触发</td>
</tr>
<tr>
<td>0 15 10 15 * ?</td>
<td>每月15日上午10:15触发</td>
</tr>
<tr>
<td>0 15 10 L * ?</td>
<td>每月最后一日的上午10:15触发</td>
</tr>
<tr>
<td>0 15 10 L-2 * ?</td>
<td>每个月的第二天到最后一天的上午10:15触发</td>
</tr>
<tr>
<td>0 15 10 ? * 6L</td>
<td>每月的最后一个星期五上午10:15触发</td>
</tr>
<tr>
<td>0 15 10 ? * 6L</td>
<td>每个月最后一个星期五上午10时15分触发</td>
</tr>
<tr>
<td>0 15 10 ? * 6L 2002-2005</td>
<td>2002年至2005年的每月的最后一个星期五上午10:15触发</td>
</tr>
<tr>
<td>0 15 10 ? * 6#3</td>
<td>每月的第三个星期五上午10:15触发</td>
</tr>
<tr>
<td>0 0 12 1/5 * ?</td>
<td>每月每隔5天下午12点（中午）触发, 从每月的第一天开始</td>
</tr>
<tr>
<td>0 11 11 11 11 ?</td>
<td>每11月11日上午11时11分触发</td>
</tr>
</tbody>
</table>
<p><img src="11.png" alt="avatar"></p>
<h2><span id="其它帮助">其它帮助</span></h2>
<p>请查看帮助文档、示例或上网搜索，：），后面有空再补充吧</p>
<h2><span id="iis应用程序池自动回收问题的有效解决办法">IIS应用程序池自动回收问题的有效解决办法</span></h2>
<p>IIS可以设置定时自动回收，默认回收是1740分钟，也就是29小时。IIS自动回收相当于服务器IIS重启，应用程序池内存清空，所有数据被清除，相当于IIS重启，在度量快速开发平台服务器端，为了减小数据库负担，内存中暂存了很多信息，不适合频繁的回收，因为回收会造成服务器端所有存在内存中的数据丢失，如果没有及时保存到数据库中，可能导致程序出现问题。而如果系统使用高峰时期，并不适合回收，回收可能导致几十秒IIS无响应，对于正在工作的人员来说，是一种很不好的体验，会以为是网络或者掉线等问题。<br>
如果IIS重启则Global.asax中的方法将被再次执行，如果不想IIS自动重启可以使用如下的设置：<br>
IIS应用程序池回收，找到相应的应用程序池并点击高级设置，就可以看到回收的相关设置<br>
<img src="12.png" alt="avatar"><br>
发生配置更改时禁止回收：如果为True,应用程序池在发生配置更改时将不会回收。<br>
固定时间间隔（分钟）：超过设置的时间后，应用程序池回收，为0意味着应用程序池不会按固定间隔回收。系统默认设置的时间是1740（29小时）。<br>
禁用重叠回收：如果为true，将发生应用程序池回收，以便在创建另一个工作进程之前退出现有工作进程。<br>
请求限制：应用程序池在回收之前可以处理的最大请求数。如果值为0，则表示应用程序池可以处理的请求数没有限制。<br>
生成回收事件日志条目：每发生一次指定的回收事件时便产生一个事件日志条目。<br>
更多参考：<a href="http://www.cnblogs.com/Fishwood/p/3602041.html" target="_blank" rel="noopener">http://www.cnblogs.com/Fishwood/p/3602041.html</a></p>
<h1><span id="总结">总结</span></h1>
<hr>
<p>1、实现定时任务的方法有很多，如果非常简单的话直接使用系统内置的Timer，Scheduler，Cache都是可以达到的，但要注意GC回收的问题，一般会定义成静态的。<br>
2、本文只是非常粗浅的介绍了一下零配置的方法，您也可以选择使用XML配置的方式替代部分的硬编码。</p>
<hr>
<!-- Place this tag in your head or just before your close body tag. -->
<script async defer src="https://buttons.github.io/buttons.js"></script>
<!-- Place this tag where you want the button to render. -->
<p>Please <a class="github-button" href="https://github.com/xyzko1/myblog" data-icon="octicon-star" aria-label="Star xyzko1/myblog on GitHub" target="_blank" rel="noopener">Star</a> this Project if you like it! <a class="github-button" href="https://github.com/xyzko1" aria-label="Follow @xyzko1 on GitHub" target="_blank" rel="noopener">Follow</a> would also be appreciated!<br>
Peace!</p>

                

                <hr>
                <!-- Pager -->
                <ul class="pager">
                    
                        <li class="previous">
                            <a href="/2019/07/21/Linq入门详解/" data-toggle="tooltip" data-placement="top" title="Linq入门详解">&larr; Previous Post</a>
                        </li>
                    
                    
                        <li class="next">
                            <a href="/2019/05/01/RabbitMq.net使用/" data-toggle="tooltip" data-placement="top" title="RabbitMq.net使用">Next Post &rarr;</a>
                        </li>
                    
                </ul>

                <!-- duoshuo Share start -->
                
                <!-- 多说 Share end-->

                <!-- 多说评论框 start -->
                
                <!-- 多说评论框 end -->

                <!-- disqus comment start -->
                
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                
                <!-- disqus comment end -->
            </div>
            
            <!-- Tabe of Content -->
            <!-- Table of Contents -->

    
      <aside id="sidebar">
        <div id="toc" class="toc-article">
        <strong class="toc-title">Contents</strong>
        
          <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.</span> <span class="toc-nav-text">Quartz.NET介绍</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">2.</span> <span class="toc-nav-text">依赖框架</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">2.1.</span> <span class="toc-nav-text">创建一个项目</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">2.2.</span> <span class="toc-nav-text">安装Nuget</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">2.3.</span> <span class="toc-nav-text">修改Nuget镜像</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">2.4.</span> <span class="toc-nav-text"></span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">2.5.</span> <span class="toc-nav-text">手动引用</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">3.</span> <span class="toc-nav-text">应用框架</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">3.1.</span> <span class="toc-nav-text">定义要执行的任务</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">3.2.</span> <span class="toc-nav-text">创建一个调度器</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">3.3.</span> <span class="toc-nav-text">创建一个任务对象</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">3.4.</span> <span class="toc-nav-text">创建一个触发器</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">3.5.</span> <span class="toc-nav-text">将任务与触发器添加到调度器中并执行</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">3.6.</span> <span class="toc-nav-text">应用关闭时结束任务</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">3.7.</span> <span class="toc-nav-text">运行结果</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">3.8.</span> <span class="toc-nav-text">Global.asax中的完整代码</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">4.</span> <span class="toc-nav-text">框架说明</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">4.1.</span> <span class="toc-nav-text">Quartz的cron表达式</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">4.2.</span> <span class="toc-nav-text">其它帮助</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">4.3.</span> <span class="toc-nav-text">IIS应用程序池自动回收问题的有效解决办法</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">5.</span> <span class="toc-nav-text">总结</span></a></li></ol>
        
        </div>
      </aside>
    

                
            <!-- Sidebar Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                
                <section>
                    <!-- no hr -->
                    <h5><a href="/tags/">FEATURED TAGS</a></h5>
                    <div class="tags">
                       
                          <a class="tag" href="/tags/#Hexo" title="Hexo">Hexo</a>
                        
                          <a class="tag" href="/tags/#Blog" title="Blog">Blog</a>
                        
                    </div>
                </section>
                

                <!-- Friends Blog -->
                
                <hr>
                <h5>FRIENDS</h5>
                <ul class="list-inline">

                    
                        <li><a href="http://beantech.org" target="_blank">Bean Tech</a></li>
                    
                        <li><a href="http://blog.kaijun.rocks" target="_blank">Kaijun&#39;s Blog</a></li>
                    
                        <li><a href="http://huangxuan.me" target="_blank">Hux Blog</a></li>
                    
                        <li><a href="#" target="_blank">It Helps SEO</a></li>
                    
                </ul>
                
            </div>
        </div>
    </div>
</article>




<!-- disqus embedded js code start (one page only need to embed once) -->
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES * * */
    var disqus_shortname = "your-disqus-ID";
    var disqus_identifier = "https://xyzko1.github.io/2019/06/23/Quartz.NET实现作业调度/";
    var disqus_url = "https://xyzko1.github.io/2019/06/23/Quartz.NET实现作业调度/";

    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<!-- disqus embedded js code start end -->




<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script>
    async("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js",function(){
        anchors.options = {
          visible: 'hover',
          placement: 'left',
          icon: 'ℬ'
        };
        anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
    })
</script>
<style>
    /* place left on bigger screen */
    @media all and (min-width: 800px) {
        .anchorjs-link{
            position: absolute;
            left: -0.75em;
            font-size: 1.1em;
            margin-top : -0.1em;
        }
    }
</style>



    <!-- Footer -->
    <!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <ul class="list-inline text-center">
                
                
                

                

                
                    <li>
                        <a target="_blank" href="https://www.facebook.com/xyzko1">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-facebook fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                
                    <li>
                        <a target="_blank"  href="https://github.com/xyzko1">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-github fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                
                    <li>
                        <a target="_blank"  href="https://www.linkedin.com/in/xyzko1">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-linkedin fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                </ul>
                <p class="copyright text-muted">
                    Copyright &copy; xyzko1 2021 
                    <br>
                    Theme by <a href="http://huangxuan.me">Hux</a> 
                    <span style="display: inline-block; margin: 0 5px;">
                        <i class="fa fa-heart"></i>
                    </span> 
                    re-Ported by <a href="http://beantech.org">BeanTech</a> | 
                    <iframe
                        style="margin-left: 2px; margin-bottom:-5px;"
                        frameborder="0" scrolling="0" width="91px" height="20px"
                        src="https://ghbtns.com/github-btn.html?user=YenYuHsuan&repo=hexo-theme-beantech&type=star&count=true" >
                    </iframe>
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/js/hux-blog.min.js"></script>


<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- 
     Because of the native support for backtick-style fenced code blocks 
     right within the Markdown is landed in Github Pages, 
     From V1.6, There is no need for Highlight.js, 
     so Huxblog drops it officially.

     - https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0  
     - https://help.github.com/articles/creating-and-highlighting-code-blocks/    
-->
<!--
    <script>
        async("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function(){
            hljs.initHighlightingOnLoad();
        })
    </script>
    <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet">
-->


<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("https://xyzko1.github.io/js/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>


<!-- Google Analytics -->


<script>
    // dynamic User by Hux
    var _gaId = 'UA-XXXXXXXX-X';
    var _gaDomain = 'yoursite';

    // Originial
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', _gaId, _gaDomain);
    ga('send', 'pageview');
</script>




<!-- Baidu Tongji -->






	<a id="rocket" href="#top" class=""></a>
	<script type="text/javascript" src="/js/totop.js?v=1.0.0" async=""></script>
    <script type="text/javascript" src="/js/toc.js?v=1.0.0" async=""></script>
<!-- Image to hack wechat -->
<img src="https://xyzko1.github.io/img/icon_wechat.png" width="0" height="0" />
<!-- Migrate from head to bottom, no longer block render and still work -->

</body>

</html>
